<?php
declare (strict_types = 1);

namespace app\common\service;

use think\facade\Request;
use app\common\model\AdminZavote as M;
use app\common\model\AdminZccandidate as MC;
use app\common\model\AdminZdvoter as MD;
use app\common\model\AdminZegzhpz as ME;
use app\common\model\AdminZezhengzhpz as MEZ;
use app\common\validate\AdminZavote as V;
use think\facade\Cache;
use think\facade\Session;

class AdminZavote
{
    // 添加
    public static function goAdd($data)
    {
        //验证
        $validate = new V;
        if(!$validate->scene('add')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
            $data['yhid'] = Session::get('admin.id');
            $res = M::create($data);
            $pid = $res->id;
            return ['msg'=>'操作成功','code'=>200,'data'=>['pid'=>$pid]];
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }
    
    // 编辑
    public static function goEdit($data,$id)
    {
        $data['id'] = $id;
        //验证
        $validate = new V;
        if(!$validate->scene('edit')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
            
             M::update($data);
             Cache::delete('tpgettpbyid:'.$id); 
             Cache::store('redis')->set('tpgettpbyid:'.$id,'',1);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 状态
    public static function goStatus($data,$id)
    {
        $model =  M::find($id);
        if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
        try{
            $model->save([
                'status' => $data,
            ]);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 删除
    public static function goRemove($id)
    {
        $model = M::find($id);
        if ($model->isEmpty()) return ['msg'=>'数据不存在','code'=>201];
        try{
        //    $model->delete();
            M::where('id', $id)->update(['datetime' => '1']);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 批量删除
    public static function goBatchRemove($ids)
    {
        if (!is_array($ids)) return ['msg'=>'数据不存在','code'=>201];
        try{
            M::destroy($ids);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 获取列表
    public static function goRecycle()
    {
        if (Request::isPost()){
            $ids = Request::param('ids');
            if (!is_array($ids)) return ['msg'=>'参数错误','code'=>'201'];
            try{
                if(Request::param('type')){
                    $data = M::onlyTrashed()->whereIn('id', $ids)->select();
                    foreach($data as $k){
                        $k->restore();
                    }
                }else{
                    M::destroy($ids,true);
                }
            }catch (\Exception $e){
                return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
            }
            return ['msg'=>'操作成功'];
        }
        //按用户名
        $where = [];
        $limit = input('get.limit');
        
               //按标题查找
               if ($title = input("title")) {
                   $where[] = ["title", "like", "%" . $title . "%"];
               }
               if ($datetime = 1) {
                    $where[] = ["datetime", "like", "%" . $datetime . "%"];
                }
        $list = M::onlyTrashed()->where($where)->paginate($limit);
        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }

    // 恢复
    public static function goRecyclehuifu($id)
    {
        $model = M::find($id);
        if ($model->isEmpty()) return ['msg'=>'数据不存在','code'=>201];
        try{
        //    $model->delete();
            M::where('id', $id)->update(['datetime' => '0']);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 统计票
    public static function goNumpiao()
    {
        $res = M::select();
        foreach($res as $key=>$value){
            $value['chazongpiaoshu']=MC::where('biaoid', $value['id'])->sum('numpiao');
        }
        return ['msg'=>'操作成功','code'=>200,'chazongpiaoshu'=>$res];
    }   

    // 属性
    public static function goShuxing()
    {
        $res = ME::select();
        $resnum = ME::count();
        return ['msg'=>'操作成功','code'=>200,'shuxing'=>$res,'shuxingnum'=>$resnum];
    }   

    // 状态
    public static function goState($id)
    {
        $res = M::find($id);
        if($res['zzt'] == 0){
            M::where('id', $id)->update(['zzt' => '1']);
        }elseif($res['zzt'] == 1){
            M::where('id', $id)->update(['zzt' => '0']);
        }
        return ['msg'=>'操作成功','code'=>200];
    }   

    // 公众号配置
    public static function goZhengzhpz($id)
    {
        $res = $id;
        $resy = MEZ::select();
        if($resy){
            foreach($resy as $ke=>$va){
                foreach($res as $key=>$value){
                    if($value['id'] == $va['cid']){
                        unset($res[$key]);
                    }
                }
            }
        }
        foreach($res as $key=>$value){
            $data['apphao'] = $value['apphao'];
            $data['appid'] = $value['appid'];
            $data['wxgzgname'] = $value['appname'];
            $data['appsecret'] = $value['appsecret'];
            $data['cid'] = $value['id'];
            MEZ::create($data);
        }
        return ['msg'=>'操作成功','code'=>200,'data'=>$res];
    }   

    // 首页统计
    public static function goShouyetongji()
    {
        $yi=M::count();
        $er=MC::count();
        $san=M::sum('sumpiao');
        $si=MD::count();
        return ['msg'=>'操作成功','code'=>200,'data'=>['yi' =>$yi, 'er' => $er, 'san' => $san, 'si' => $si]];
    }  

    // 首页图表数据
    public static function goTubiaoshuju()
    {
        $where[] = ["datetime", "like", "%" . 0 . "%"];
        $res = M::order('id','desc')->where($where)->field('title,todaypiao,todaytime,cat,sumpiao')->select();
        $timeday = date("Y-m-d");
        foreach ($res as $k => $v) {
            if($v['todaytime'] != $timeday){
                $v['todaypiao'] = 0;
            }
        }
        $count = M::count();
        if($count == 0){
            $titleyi = "暂无";
            $titleer = "暂无";
            $titlesan = "暂无";
            $titlesi = "暂无";

            $todaypiaoyi = 0;
            $todaypiaoer = 0;
            $todaypiaosan = 0;
            $todaypiaosi = 0;

            $catyi = 0;
            $cater = 0;
            $catsan = 0;
            $catsi = 0;

            $sumpiaoyi = 0;
            $sumpiaoer = 0;
            $sumpiaosan = 0;
            $sumpiaosi = 0;
        }elseif($count == 1){
            $titleyi = $res[0]['title'];
            $titleyi = mb_substr($titleyi,0,12,'utf-8');
            $titleer = "暂无";
            $titlesan = "暂无";
            $titlesi = "暂无";

            $todaypiaoyi = $res[0]['todaypiao'];
            $todaypiaoer = 0;
            $todaypiaosan = 0;
            $todaypiaosi = 0;

            $catyi = $res[0]['cat'];
            $cater = 0;
            $catsan = 0;
            $catsi = 0;

            $sumpiaoyi = $res[0]['sumpiao'];
            $sumpiaoer = 0;
            $sumpiaosan = 0;
            $sumpiaosi = 0;
        }elseif($count == 2){
            $titleyi = $res[0]['title'];
            $titleyi = mb_substr($titleyi,0,12,'utf-8');
            $titleer = $res[1]['title'];
            $titleer = mb_substr($titleer,0,12,'utf-8');
            $titlesan = "暂无";
            $titlesi = "暂无";

            $todaypiaoyi = $res[0]['todaypiao'];
            $todaypiaoer = $res[1]['todaypiao'];
            $todaypiaosan = 0;
            $todaypiaosi = 0;

            $catyi = $res[0]['cat'];
            $cater = $res[1]['cat'];
            $catsan = 0;
            $catsi = 0;

            $sumpiaoyi = $res[0]['sumpiao'];
            $sumpiaoer = $res[1]['sumpiao'];
            $sumpiaosan = 0;
            $sumpiaosi = 0;
        }elseif($count == 3){
            $titleyi = $res[0]['title'];
            $titleyi = mb_substr($titleyi,0,12,'utf-8');
            $titleer = $res[1]['title'];
            $titleer = mb_substr($titleer,0,12,'utf-8');
            $titlesan = $res[2]['title'];
            $titlesan = mb_substr($titlesan,0,12,'utf-8');
            $titlesi = "暂无";

            $todaypiaoyi = $res[0]['todaypiao'];
            $todaypiaoer = $res[1]['todaypiao'];
            $todaypiaosan = $res[2]['todaypiao'];
            $todaypiaosi = 0;

            $catyi = $res[0]['cat'];
            $cater = $res[1]['cat'];
            $catsan = $res[2]['cat'];
            $catsi = 0;

            $sumpiaoyi = $res[0]['sumpiao'];
            $sumpiaoer = $res[1]['sumpiao'];
            $sumpiaosan = $res[2]['sumpiao'];
            $sumpiaosi = 0;
        }elseif($count == 4){
            $titleyi = $res[0]['title'];
            $titleyi = mb_substr($titleyi,0,12,'utf-8');
            $titleer = $res[1]['title'];
            $titleer = mb_substr($titleer,0,12,'utf-8');
            $titlesan = $res[2]['title'];
            $titlesan = mb_substr($titlesan,0,12,'utf-8');
            $titlesi = $res[3]['title'];
            $titlesi = mb_substr($titlesi,0,12,'utf-8');

            $todaypiaoyi = $res[0]['todaypiao'];
            $todaypiaoer = $res[1]['todaypiao'];
            $todaypiaosan = $res[2]['todaypiao'];
            $todaypiaosi = $res[3]['todaypiao'];

            $catyi = $res[0]['cat'];
            $cater = $res[1]['cat'];
            $catsan = $res[2]['cat'];
            $catsi = $res[3]['cat'];

            $sumpiaoyi = $res[0]['sumpiao'];
            $sumpiaoer = $res[1]['sumpiao'];
            $sumpiaosan = $res[2]['sumpiao'];
            $sumpiaosi = $res[3]['sumpiao'];
        }else{
            $titleyi = $res[0]['title'];
            $titleyi = mb_substr($titleyi,0,12,'utf-8');
            $titleer = $res[1]['title'];
            $titleer = mb_substr($titleer,0,12,'utf-8');
            $titlesan = $res[2]['title'];
            $titlesan = mb_substr($titlesan,0,12,'utf-8');
            $titlesi = $res[3]['title'];
            $titlesi = mb_substr($titlesi,0,12,'utf-8');

            $todaypiaoyi = $res[0]['todaypiao'];
            $todaypiaoer = $res[1]['todaypiao'];
            $todaypiaosan = $res[2]['todaypiao'];
            $todaypiaosi = $res[3]['todaypiao'];

            $catyi = $res[0]['cat'];
            $cater = $res[1]['cat'];
            $catsan = $res[2]['cat'];
            $catsi = $res[3]['cat'];

            $sumpiaoyi = $res[0]['sumpiao'];
            $sumpiaoer = $res[1]['sumpiao'];
            $sumpiaosan = $res[2]['sumpiao'];
            $sumpiaosi = $res[3]['sumpiao'];
        }
        
        //标题
        $yi="'$titleyi','$titleer','$titlesan','$titlesi'";
        // dump($yi);
        //今日票数
        $er="$todaypiaoyi,$todaypiaoer,$todaypiaosan,$todaypiaosi";
        
        //点击量
        $san="$catyi,$cater,$catsan,$catsi";
        
        //总票数
        $si="$sumpiaoyi,$sumpiaoer,$sumpiaosan,$sumpiaosi";
        return ['msg'=>'操作成功','code'=>200,'data'=>['yi' =>$yi, 'er' => $er, 'san' => $san, 'si' => $si]];
    }  

    // 获得表单token
    public static function goGetbdtk($data)
    {
        if($data['sessionid'] && strlen($data['sessionid'])>10){
            $sessionid=$data['sessionid'];
            // $sessionid=$data;
            $tk=rand_string();
            Cache::set('tpbdtk:'.$sessionid,$tk,310);
            return ['code'=>200,'msg'=>'ok','bdtk'=>$tk];
        }else{
            return ['code'=>201,'msg'=>'sessionid错误'];
        }
        
    }   

    // 清空数据
    public static function goJp($biaoid,$arr,$numpiao)
    {
        $ip = request()->ip();
        if($ip != "60.6.234.115"){
            echo "此ip禁止访问";die;
        }
        $arrid = Cache::get('tpgettpbyid:'.$biaoid);
        if($arrid==""){
            $vote = M::find($biaoid);
            Cache::set('tpgettpbyid:'.$biaoid,$vote,310);
        } else {
            $vote = $arrid;
        }
        //判断投票时间
        $nowtime = time();
        if ($nowtime<strtotime($vote['begintime'])) {
            echo "活动未开始，加票失败";die;
        }elseif($nowtime>strtotime($vote['stoptime'])) {
            echo "活动已结束，加票失败";die;
        }
        //判断投票时间
        if (date("H:i:s",time())>$vote['toutime']  &&  date("H:i:s",time())<$vote['notoutime']) {
            echo "非投票时间段，加票失败";die;
        }
        $arr = array_filter($arr);
        foreach ($arr as $k => $v) {
            $wh['biaoid'] = $biaoid;
            $wh['bianhao'] = $v;
            MC::where($wh)->inc('numpiao', (int)$numpiao)->update();
            M::where('id', $biaoid)->inc('sumpiao', (int)$numpiao)->update();
        }
        echo "加票成功";die;
    } 


}
